/*
 * Copyright (c) 2025 GuoKaiHong (Shenzhen) Technology Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import { BusinessError } from '@ohos.base'
import util from '@ohos.util';
import log from './Log'
import { common, Context } from '@kit.AbilityKit';

/**
 * 文件工具类
 */
export class FileUtils {
  static TAG = "FileUtils";

  /**
   * 读取rawfile内容
   *
   * @param context 上下文
   * @param path rawfile文件名（包括后缀）
   * @returns Promise对象
   */
  static getRawFileContent(context: common.UIAbilityContext, path: string): Promise<Uint8Array> {
    try {
      // promise方式读取rawfile内容
      return context.resourceManager.getRawFileContent(path)
    } catch (error) {
      let code = (error as BusinessError).code;
      let message = (error as BusinessError).message;
      log(FileUtils.TAG, `callback getRawFileContent failed, error code: ${code}, message: ${message}.`)
    }
    return null;
  }

  /**
   * Uint8Array转换字符串
   *
   * @param uint8Array Uint8Array对象
   * @returns 字符串
   */
  static uint8Array2Str(uint8Array: Uint8Array): string {
    let decoder = util.TextDecoder.create('utf-8', { ignoreBOM: false });
    return decoder.decodeToString(uint8Array, { stream: false });
  }
}